import { createRouter, createWebHashHistory } from 'vue-router';
import routes from './routes';
import store from '@/store';
import { Toast } from 'vant';

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

// 前置守卫
router.beforeEach(async (to, _, next) => {
    const unsafe = ['/person', '/store', '/update'];
    if (unsafe.includes(to.path)) {
        // 进入这三个路由都需要保证当前是登录状态，如果是未登录则调到login页面
        let { isLogin } = store.state;
        if (isLogin === null) {
            // 登录状态未知，则派发请求
            isLogin = await store.dispatch('changeIsLoginAsync');
        }
        if (isLogin === false) {
            Toast.fail('请您先登录~~');
            next(`/login?to=${to.path}`);
            return;
        }
    }
    next();
});

export default router;